package com.szl.mail;

import com.rabbitmq.client.Channel;
import com.szl.yeb.common.constant.MailConstant;
import com.szl.yeb.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;

/**
 * @program: yeb
 * @description: 监听消息并发送邮件
 * @author: szl
 * @create: 2022-09-03 23:19
 **/
@Component
@Slf4j
public class MailProcessor {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private MailProperties mailProperties;

    @Autowired
    private TemplateEngine templateEngine;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @RabbitListener(queues = MailConstant.MAIL_QUEUE_NAME)
    public void messageHandler(Message message, Channel channel) {

        Employee employee = (Employee) message.getPayload();

        MessageHeaders headers = message.getHeaders();

        Long tag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        String msgId = (String) headers.get("spring_returned_message_correlation");

        HashOperations<Object, Object, Object> opsForHash = redisTemplate.opsForHash();


        try {
            if (opsForHash.entries("mail_log").containsKey(msgId)) {
                log.info("{}:消息已被消费", msgId);
                channel.basicAck(tag, false);
                return;
            }

            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);

            mimeMessageHelper.setFrom(mailProperties.getUsername());
            mimeMessageHelper.setTo(employee.getEmail());
            mimeMessageHelper.setSubject("入职欢迎邮件");
            mimeMessageHelper.setSentDate(new Date());

            Context context = new Context();

            context.setVariable("name", employee.getName());
            context.setVariable("posName", employee.getPosition().getName());
            context.setVariable("joblevelName", employee.getJoblevel().getName());
            context.setVariable("departmentName", employee.getDepartment().getName());

            String mail = templateEngine.process("mail", context);

            mimeMessageHelper.setText(mail, true);

            javaMailSender.send(mimeMessage);

            log.info("邮件发送成功");

            assert msgId != null;
            opsForHash.put("mail_log", msgId, "OK");

            channel.basicAck(tag, false);

        } catch (Exception e) {

            e.printStackTrace();
            log.error("邮件发送失败:{}", e.getMessage());

            try {
                channel.basicNack(tag, false, true);
            } catch (IOException ex) {
                ex.printStackTrace();
                log.error("邮件发送失败:{}", e.getMessage());
            }

        }
    }
}
